package com.tfjybj.itoo.exam.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.mail.util.MailSSLSocketFactory;
import com.tfjybj.itoo.exam.entity.*;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.dao.ExamRoomDao;
import com.tfjybj.itoo.exam.provider.service.*;
import com.tfjybj.itoo.exam.template.ExamRoomStuTeaModel;
import com.tfjybj.itoo.exam.template.ScreenClassStu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.transaction.Transactional;
import java.security.GeneralSecurityException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ExamRoomService接口实现类
 * ${base}表
 *
 * @author 任晓帅
 * @version 2.0.0
 * @since 2.0.0 2018-11-15 19:40:28
 */
@Slf4j
@Service("examRoomService")
public class ExamRoomServiceImpl extends BaseServicePlusImpl<ExamRoomDao, ExamRoomEntity> implements ExamRoomService {

    private final static String HOST = "smtp.tfjybj.com"; //163的服务器
    private final static String FORM_NAME = "itoo@tfjybj.com";//你的邮箱
    private final static String PASS_WORD = "TGB123@tgb"; //授权码
    private final static String REPLAY_ADDRESS = "18631687403@163.com"; //你的邮箱
    @Resource
    private ExamRoomDao examRoomDao;
    @Resource
    private TeacherCourseService teacherCourseService;
    @Resource
    private ExaminationService examinationService;
    @Resource
    private StaffService staffService;
    @Resource
    private ExamineeService examineeService;
    @Resource
    private DisciplineInfoService disciplineInfoService;
    @Resource
    private CourseScheduleService courseScheduleService;
    @Resource
    private StudentService studentService;
    @Resource
    private RoomService roomService;
    @Resource
    private ClassService classService;
    @Resource
    private ProfessionService professionService;
    @Resource
    private AcademyService academyService;

    @Override
    public PageInfo<ExamRoomEntity> queryByLikeName(String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(examRoomDao.queryLikeName(name));
    }

    //endregion

    /* **********************************以下为非模板生成的内容********************************* */


    /**
     * 查询考场信息、缺考、违纪详情
     *
     * @param courseId,examNameId
     * @return exam ExaminationModel
     * @author 王雪芬
     * @since 2.0.0 2018-11-19 12:14:07
     */
    @Override
    public List<ExamRoomModel> queryExaminRoot(String courseId, String examNameId) {

        /*查询出相关考试所有的考场信息*/
        List<ExamRoomModel> examRoomModels = examinationService.queryExamRoomInfo(courseId, examNameId);
        /*查询考场中所有的考生信息*/
        for (ExamRoomModel examRoomModel : examRoomModels) {
            String examId = examRoomModel.getExamId();
            String examRoomId = examRoomModel.getRoomId();
            /*当前考场下的所有考生明细*/
            List<ExamineeReachClassModel> studentInfoList = examineeService.queryExamStudent(examId, examRoomId);
            examRoomModel.setStudentInfoList(studentInfoList);
            examRoomModel.setEmployCapacity(studentInfoList.size());
            /*考场中考生的违纪信息明细*/
            List<DisciplineInfoModel> disciplineInfoList = disciplineInfoService.queryDisciplineStudent(examId, examRoomId);
            examRoomModel.setDisciplineInfoList(disciplineInfoList);
            /*当前考场中违纪人数*/
            Integer disciplineNum = disciplineInfoService.queryDisciplineCount(examId, examRoomId);
            examRoomModel.setDisciplineNum(disciplineNum);
            /*当前考场中考生的缺考信息*/
            List<ExamineeModel> noLoginExamineeList = examineeService.queryExamStudentNologin(examId, examRoomId);
            examRoomModel.setNoLoginExamineeList(noLoginExamineeList);
            /*当前考场中考生缺考人数*/
            examRoomModel.setNoLoginNum(noLoginExamineeList.size());
            /*主监考老师*/
            String teacherName = staffService.getById(examRoomModel.getInvigilatorMainId()).getName();
            examRoomModel.setTeacherName(teacherName);
        }
        return examRoomModels;
    }


//    /**
//     * 查询考场详情
//     * @param model ExaminationModel
//     * @return exam ExaminationModel
//     * @author 王雪芬
//     * @since 2.0.0 2018-11-19 12:14:07
//     */
//    @Override
//
//    public HashMap<String, ExamRoomModel> queryExaminRoot(ExaminationModel model) {
//
//        ExaminationModel examinationSEndModels = new ExaminationModel();
//        ExaminationModel examinationModels =new ExaminationModel();
//        //1. 3个条件都不为空,按照时间,课程,考场查询
//        if (model.getCourseId() != null && model.getId() != null && model.getStartTime() != null && model.getEndTime() != null) {
//            examinationModels = examinationService.queryExamTime(model.getId(), model.getCourseId(), model.getStartTime(), model.getEndTime());
//            if (examinationModels == null) {
//                return null;
//            }
//            BeanUtils.copyProperties(examinationModels, model);
//        }
//        //2. 如果按照时间进行查询所有考场
//        if (model.getCourseId() == null && model.getId() == null && model.getStartTime() != null && model.getEndTime() != null) {
//            examinationSEndModels = examinationService.queryExamSETime(model.getStartTime(), model.getEndTime());
//            if (examinationSEndModels == null) {
//                return null;
//
//            }
//            BeanUtils.copyProperties(examinationSEndModels, model);
//        }
//        //3 按照考场查询
//        //教师ids
//        List<String> teacherList = new ArrayList<>();
//        //存放教师
//        HashMap<String, TeacherCourseEntity> teachClassMap = new HashMap<>();
//        //存放学生
//        HashMap<String, List<ExamineeReachClassModel>> studentClassMap = new HashMap<>();
//        //违纪
//        HashMap<String, List<DisciplineInfoModel>> disciplineMap = new HashMap<>();
//        //缺考
//        HashMap<String, List<ExamineeModel>> noLoginStudentMap = new HashMap<>(16);
//        // 全局
//        HashMap<String, ExamRoomModel> examInfoMap = new HashMap<>();
//        //存放所有明细
//        ExamRoomModel examineeReachClassModels = new ExamRoomModel();
//        List<ExamRoomModel> examRoomModelList = examRoomDao.queryExaminRoot(model);
//        examRoomModelList.removeAll(Collections.singleton(null));
//        if (CollectionUtils.isEmpty(examRoomModelList)) {
//            return null;
//        }
//        for (ExamRoomModel examRoomModel : examRoomModelList) {
//            /**
//             *  考场下所有学生
//             */
//            List<ExamineeReachClassModel> studentClassList;
//            //查看该考场下所有学生
//            studentClassList = examineeService.queryExamStudent(examRoomModel.getExamId());
//            studentClassList.removeAll(Collections.singleton(null));
//            if (!CollectionUtils.isEmpty(studentClassList)) {
//                //考场id,考场学生
//                studentClassMap.put(examRoomModel.getId(), studentClassList);
//                examineeReachClassModels.setStudentInfoList(studentClassMap.get(examRoomModel.getId()));
//                // 总人数
//                examineeReachClassModels.setEmployCapacity(studentClassList.size());
//            }
//
//            /*该考场下所有违纪学生*/
//            List<DisciplineInfoModel> disciplineList;
//            disciplineList = disciplineInfoService.queryDisciplineStudent(examRoomModel.getExamId());
//            //违纪人数初始化为0
//
//            int disciplineNum = 0;
//
//            if (!CollectionUtils.isEmpty(disciplineList) && disciplineList.size() == 0) {
//                disciplineNum = disciplineInfoService.queryDisciplineCount(examRoomModel.getExamId());
//            }
//
//            if (!CollectionUtils.isEmpty(disciplineList)) {
//                disciplineMap.put(examRoomModel.getId(), disciplineList);
//                examineeReachClassModels.setDisciplineInfoList(disciplineMap.get(examRoomModel.getId()));
//
//                //违纪人数
//                int finalDisciplineNum = disciplineNum;
//                disciplineMap.get(examRoomModel.getId()).forEach(disciplineInfoModel -> examineeReachClassModels.setDisciplineNum(finalDisciplineNum));
//            }
//
//            /*查看该考场下所有缺考学生*/
//            List<ExamineeModel> noLoginStudentlist;
//            noLoginStudentlist = examineeService.queryExamStudentNologin(examRoomModel.getExamId());
//            noLoginStudentlist.removeAll(Collections.singleton(null));
//
//            if (!CollectionUtils.isEmpty(noLoginStudentlist)) {
//                noLoginStudentMap.put(examRoomModel.getId(), noLoginStudentlist);
//                examineeReachClassModels.setNoLoginExamineeList(noLoginStudentMap.get(examRoomModel.getId()));
//
//                noLoginStudentMap.get(examRoomModel.getId()).forEach(examineeReachClassModel -> examineeReachClassModels.setNoLoginNum(noLoginStudentlist.size()));
//            }
//
//            ExaminationEntity examinationEntity = examinationService.getById(model.getId());
//            TeacherCourseEntity teachClassEntity = new TeacherCourseEntity();
//            if (examinationEntity != null && examinationEntity.getOperator() != null) {
//                /*查看该考场下的所有监考老师*/
//                teachClassEntity = teacherCourseService.queryCourseTeacher(examinationEntity.getOperator());
//            }
//
//
//            if (teachClassEntity != null) {
//                teachClassMap.put(examRoomModel.getId(), teachClassEntity);
//                examineeReachClassModels.setTeacherName(teachClassMap.get(examRoomModel.getId()).getTeacherName());
//            }
//            if (!StringUtils.isEmpty(examRoomModel.getName())) {
//                examineeReachClassModels.setName(examRoomModel.getName());
//            }
//            //汇总
//            examInfoMap.put(examRoomModel.getId(), examineeReachClassModels);
//        }
//        return examInfoMap;
//    }

    /**
     * @param examId string
     * @return 删除条数
     * @author maying
     * @since 2018年11月18日10:19:20
     */
    @Override
    public int delExamroomArray(String examId) {
        return examRoomDao.delExamroomArray(examId);
    }

    /**
     * @param examId
     * @return 考场List
     * @author maying
     * @since 2018年11月18日16:00:38
     * 根据考试id查询考场
     */
    @Override
    public List<ExamRoomEntity> selexamRoom(String examId) {
        /**
         * 1,先查看本场考试下面是插入考场还是更新考场,一般情况更新的时候考试下面是没有考场的,另一种情况就是考场全部占满也是没有数据的
         * 2/先查看班级是否有学生
         * 3.上面都确定之后再次去调取本方法
         */
        // 第一步,判断是否有数据
        List<ExamRoomEntity> examRoomEntities;
        examRoomEntities = examRoomDao.selAddExaminee(examId);
        if (examRoomEntities.size() == 0) {
            // 查看本考试下面是否存在考生
            List<ExamineeModel> examineeModelList = examineeService.selectCountExaminee(examId);
            if (examineeModelList.size() > 0) {
                // 查看考生属于的考场
                examRoomEntities = examineeService.selectExamineeInExamRoom(examId);
            }
        }

        return examRoomEntities;
    }

    /**
     * 根据操作人和查询正在进行的考试
     *
     * @param operator String
     * @return 考场信息
     * @author 王雪芬
     * @since 2018年11月22日10:19:20
     */
    @Override
    public List<ExamRoomModel> queryExamRoom(String operator) {
        return examRoomDao.queryExamRoom(operator);
    }


    @Override
    public int sendExamWorkInfo(MailInfoModel info) {

        info.setSubject("考试情况通报表");
        info.setToAddress("18631687403@163.com");
        // 发件人电子邮箱
        final String from = "itoo@tfjybj.com";
        // 发件人电子邮箱密码
        final String pass = "TGB123@tgb";
        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.tfjybj.com"; // 邮件服务器
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.HOST", host);
        properties.put("mail.smtp.auth", "true");


        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);


        // 获取默认session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("18631687403@163.com"
            ));

            // Set Subject: 主题文字
            message.setSubject(info.getSubject());


            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();


            messageBodyPart.setContent(info.getContent(), "text/html; charset=utf-8");
            System.out.println(message.getContentID());


            // 创建多重消息/ MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
            Multipart mainPart = new MimeMultipart();

            mainPart.addBodyPart(messageBodyPart);
            System.out.println(mainPart.getCount());
            // 将MiniMultipart对象设置为邮件内容
            message.setContent(mainPart);
            // 发送消息
            Transport.send(message);
            return 1;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return 0;
    }


//    public int sendExamWorkInfo(MailInfoModel info) {
//        info.setHost(HOST);
//        info.setFormName(FORM_NAME);
//        info.setFormPassword(PASS_WORD);   //网易邮箱的授权码~不一定是密码
//        info.setReplayAddress(REPLAY_ADDRESS);
//
//        Message message = null;
//        try {
//            message = getMessage(info);
//            // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
//            Multipart mainPart = new MimeMultipart();
//            // 创建一个包含HTML内容的MimeBodyPart
//            BodyPart html = new MimeBodyPart();
//            // 设置HTML内容
//            html.setContent(info.getContent(), "text/html; charset=utf-8");
//            mainPart.addBodyPart(html);
//            // 将MiniMultipart对象设置为邮件内容
//            message.setContent(mainPart);
//            Transport.send(message);
//            return 1;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return 0;
//    }

//    private Message getMessage(MailInfoModel info) throws Exception {
//
//        final Properties p = System.getProperties();
//        p.setProperty("mail.smtp.HOST", info.getHost());
//        p.setProperty("mail.smtp.auth", "true");
//        p.setProperty("mail.smtp.user", info.getFormName());
//        p.setProperty("mail.smtp.pass", info.getFormPassword());
//
//        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
//        Session session = Session.getInstance(p, new Authenticator() {
//            protected PasswordAuthentication getPasswordAuthentication() {
//                return new PasswordAuthentication(info.getFormName(), info.getFormPassword());
//            }
//        });
//        session.setDebug(true);
//        Message message = new MimeMessage(session);
//        //消息发送的主题
//        message.setSubject(info.getSubject());
//        //接受消息的人
//        message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
//        //消息的发送者
//        message.setFrom(new InternetAddress(info.getFormName(), "王雪芬"));
//        // 创建邮件的接收者地址，并设置到邮件消息中
//        message.setRecipient(Message.RecipientType.TO, new InternetAddress("18631687403@163.com"));
//        // 消息发送的时间
//        message.setSentDate(new Date());
//        return message;
//    }
//

    /**
     * 完成选择时插入考场和人数以及监考老师
     *
     * @param jsonList
     * @author maying
     * @since 2018-12-14 08:48:08
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean saveStuExamRoom(ExamRoomStuTeaModel jsonList) {
        // 定义一个学生数组接收学生集合
        List<ScreenClassStu> studentArray = new ArrayList<>();
        // 排序完成之后整合到一个数组中
        jsonList.getStudentArray().stream().collect(Collectors.groupingBy(ScreenClassStu::getClassName)).forEach((String mapKey, List<ScreenClassStu> stuList) -> {
            studentArray.addAll(stuList);
        });
        // 接收考场集合
        List<RoomModel> roomArray = jsonList.getRoomArray();

        // 监考老师集合
        List<StaffModel> teacherArray = jsonList.getTeacherArray();

        // 创建考试信息
        ExaminationModel createExam = jsonList.getCreateExam();

        // 定义一个接收学院信息的map
        Map<String, AcademyEntity> academyEntityMap = new HashMap<>();
        // 定义考生所在专业map
        Map<String, ProfessionEntity> professionMap = new HashMap<>();

        // 定义考生所在的班级map
        Map<String, ClassEntity> classEntityMap = new HashMap<>();
        // 定义一个以班级id为key的map
        Map<String, List<StudentModel>> classListMap = new HashMap<>();
        // 根据考试开始和结束时间查询所有跟这俩时间有冲突的所有考场和监考老师
        /**
         * 本环节的思路
         * 1. 先查询所有的要查询的(考场,考生,监考老师)
         */
        // 根据考试的开始时间和结束时间查询考场
        List<ExamRoomModel> examRoomModelList = examRoomDao.queryMeetConditionExamRoom(createExam.getStartTime(), createExam.getEndTime());
        // 根据考试的开始时间和结束时间查询考生
        List<ExamineeModel> examineeModelList = examineeService.queryMeetConditionExaminnee(createExam.getStartTime(), createExam.getEndTime());
        //根据考试的开始时间和结束时间查询监考老师
        List<String> teacherIdList = examRoomDao.queryTeacherIdList(createExam.getStartTime(), createExam.getEndTime());


        // 判断新配置的考生是否与其他已经配置的考生有冲突
        Collection exists = new ArrayList<>(studentArray.stream().map(ScreenClassStu::getKey).collect(Collectors.toList()));
        Collection notexists = new ArrayList<>(studentArray.stream().map(ScreenClassStu::getKey).collect(Collectors.toList()));
        // 去除有冲突的考生,剩下就是么有安排过的考生id
        exists.removeAll(examineeModelList.stream().map(ExamineeModel::getStudentId).collect(Collectors.toList()));
        // 查看冲突的考生 (notexists 集合)id
        notexists.removeAll(exists);
        if (notexists.size() > 0) {
            return false;
        }
        // 判断新配置的监考老师是否与其他已经配置的监考老师有冲突
        Collection existsTeacher = new ArrayList<>(teacherArray.stream().map(StaffModel::getId).collect(Collectors.toList()));
        Collection notexistsTeacher = new ArrayList<>(teacherArray.stream().map(StaffModel::getId).collect(Collectors.toList()));
        // 去除有冲突的考生,剩下就是么有安排过的考生id
        existsTeacher.removeAll(teacherIdList);
        // 查看冲突的考生 (notexists 集合)id
        notexistsTeacher.removeAll(existsTeacher);
        if (notexists.size() > 0) {
            return false;
        }
        // 定义接收学生索引
        int stuIndexes = 0;
        // 监考老师索引
        int invigilatorIndexes = 0;
        for (RoomModel roomModel : roomArray) { // 循环考场信息
            // 设置默认考场大小
            roomModel.setDistributivePersonNumber(roomModel.getDistributivePersonNumber() > 0 ? roomModel.getDistributivePersonNumber() : roomModel.getRoomCapacity());
            // 根据考试的开始时间和结束时间查询考场,查询是否有本次配置的考场,以防冲突
//            if (examRoomModelList.stream().filter(x -> x.getId().equals(roomModel.getId())).count() > 0 ? (examRoomModelList.stream().filter(x -> x.getId().equals(roomModel.getId())).count() > 0 ? (examRoomModelList.stream().filter(x -> x.getId().equals(roomModel.getId())).min(Comparator.comparingInt(ExamRoomModel::getEmployCapacity)).get().getEmployCapacity() < roomModel.getDistributivePersonNumber()) : false) : false) {
//                return false;
//            }
            Stream<ExamRoomModel> examRoomModelStream = examRoomModelList.stream().filter(x -> x.getId().equals(roomModel.getId()));
            if (examRoomModelStream.count() > 0) {
                if (examRoomModelStream.min(Comparator.comparingInt(ExamRoomModel::getEmployCapacity)).get().getEmployCapacity() < roomModel.getDistributivePersonNumber()) {
                    return false;
                }
            }

            // 根据考试的开始时间和结束时间查询考场,查询是否有本次配置的考生,以防冲突

            // 使用雪花算法获取考场id
            String examRoomId = IdWorker.getIdStr();
            // 计算理论交卷时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createExam.getStartTime());
            calendar.set(Calendar.MINUTE, createExam.getExamDuration());
            // 声明一个考场实体,准备向考场表中插入考场信息
            ExamRoomEntity examRoomEntity = new ExamRoomEntity();
            // 获取考场名称,截取一些不必要的信息
            examRoomEntity.setName(roomModel.getName().substring(0, roomModel.getName().lastIndexOf('-') - 1))
                    .setRoomId(roomModel.getId())
                    .setExamId(createExam.getId())
                    .setRoomCapacity(roomModel.getRoomCapacity())
                    // 考场剩余容量
                    .setEmployCapacity(roomModel.getRoomCapacity() - roomModel.getDistributivePersonNumber())
                    .setOperator(createExam.getOperator());
            // 考试开始时间
            examRoomEntity.setLoginTime(createExam.getStartTime())
                    // 考试理论交卷时间
                    .setShouldSubmitTime(calendar.getTime())
                    // 插入主监考教师
                    .setInvigilatorMainId(teacherArray.get(invigilatorIndexes).getId())
                    .setId(examRoomId);
            // 监考老师索引下一个
            invigilatorIndexes++;

            // 定义考生集合
            List<ExamineeEntity> examineeEntityArrayList = new ArrayList<>();
            if (this.save(examRoomEntity)) {
                // 将考试id插入对应的roomArray中
                roomArray.stream().filter(x -> x.id.equals(roomModel.getId())).findFirst().get().setExamRoomId(examRoomId);
                int stuSumNumber = roomModel.getDistributivePersonNumber();
                stuIndexes += stuSumNumber;
                // 筛选插入考场的人数,每次根据考场容量筛选考生
                List<ScreenClassStu> stuStream = studentArray.stream().limit(stuIndexes).skip(stuIndexes - stuSumNumber).collect(Collectors.toList());
                /**
                 * 判断考场使用的位置和考生人数之间的关系,避免大量浪费
                 * 思路: 首先判断插入考生人数,然后在跟考场使用的数量作对比,不符合规定怎更新考场
                 */
                if (stuStream.size() < stuSumNumber) {
                    ExamRoomEntity examRoom = new ExamRoomEntity();
                    examRoom.setId(examRoomId);
                    examRoom.setEmployCapacity(roomModel.getRoomCapacity() - stuStream.size());
                    examRoomDao.updateById(examRoom);
                }
                stuStream.forEach((ScreenClassStu screenClassStu) -> {
                    ExamineeEntity examineeEntity = new ExamineeEntity();
                    // 根据班级id分类,查询整个班级的学生,从中根据学生id筛选考生信息,最后结果筛选出合适的学生信息(获取学生信息,这样子减少访问数据库次数)
                    StudentModel studentModel = classListMap.computeIfAbsent(screenClassStu.getClassesId(), k -> studentService.findByClassId(screenClassStu.getClassesId())).stream().filter(x -> x.getId().equals(screenClassStu.getKey())).findFirst().get();

                    examineeEntity.setStudentName(studentModel.getName())
                            .setStudentId(studentModel.getId())
                            .setStudentCode(studentModel.getCode())
                            .setClassName(studentModel.getClassesName())
                            .setClassId(studentModel.getClassesId())
                            .setClassName(studentModel.getClassesName())
                            .setMajorId(studentModel.getProfessionId())
                            .setCollegeId(studentModel.getAcademyId())
                            .setExamRoomId(examRoomId)
                            .setExaminationId(createExam.getId())
                            .setOperator(createExam.getOperator());
                    examineeEntity.setStudentExamState(0);
                    // 查询学院信息(使用map)
                    AcademyEntity academyEntity = academyEntityMap.computeIfAbsent(studentModel.getAcademyId(), k -> academyService.getById(studentModel.getAcademyId()));
                    if (academyEntity != null) {
                        examineeEntity.setCollegeName(academyEntity.getName());
                    }
//                    查询专业信息(使用map)
                    ProfessionEntity professionEntity = professionMap.computeIfAbsent(studentModel.getProfessionId(), k -> professionService.getById(studentModel.getProfessionId()));
                    if (professionEntity != null) {
                        examineeEntity.setMajorName(professionEntity.getName());
                    }
//                    收集考试信息
                    examineeEntityArrayList.add(examineeEntity);
                });
            }
            // 插入学生
            boolean saveBatch = examineeService.saveBatch(examineeEntityArrayList);
        }
        //  考场根据使用的用量来进行降序排序,并且更新副监考老师
        for (RoomModel roomModel : roomArray.stream().sorted(Comparator.comparing(RoomModel::getDistributivePersonNumber).reversed()).collect(Collectors.toList())) {
            if (teacherArray.size() > invigilatorIndexes) {
                ExamRoomEntity examRoom = new ExamRoomEntity();
                examRoom.setId(roomModel.getExamRoomId());
                examRoom.setInvigilatorSubId(teacherArray.get(invigilatorIndexes).getId());
                examRoomDao.updateById(examRoom);
                invigilatorIndexes++;
            }
        }
        // 收集考试信息
        ExaminationEntity examinationEntity = new ExaminationEntity();
        examinationEntity.setId(createExam.getId());
        examinationEntity.setIsEvaluation(createExam.getIsEvaluation())
                .setEvaluationPaperId(createExam.getEvaluationPaperId())
                .setExamDuration(createExam.getExamDuration())
                .setStartTime(createExam.getStartTime())
                .setExamName(createExam.getExamName())
                .setExamClassifyId(createExam.getClassifyId())
                .setOperator(createExam.getOperator());
        // 更新考试信息
        boolean examById = examinationService.updateById(examinationEntity);
        return examById;
    }

    /**
     * 查询已安排有剩余容量的考场
     *
     * @param schoolKey 校区代号
     * @param startTime 开始考试时间
     * @param endTime   考试结束时间
     * @author maying
     * @since 2018-12-20 16:01:55
     */
    @Override
    public List<ExamRoomModel> selectSurplusRoom(String fuzzyValue, String schoolKey, String startTime, String endTime) {
        return examRoomDao.selectSurplusRoom(fuzzyValue, schoolKey, startTime, endTime);
    }

    /**
     * 点击考场选择按钮,判断此考场是否选择过
     *
     * @param roomId     教室id
     * @param schoolCode 校区代号
     * @param startTime  考试开始时间
     * @author 马莹
     * @since 2018-12-21 12:00:17
     */
    @Override
    public List<ExamRoomModel> selectExamRoom(String roomId, String schoolCode, String startTime) {
        return examRoomDao.selectExamRoom(roomId, schoolCode, startTime);
    }

    /**
     * 根据考试id查询所有监考老师,对应考场
     *
     * @param examId      考试id
     * @param teacherName 模糊参数
     * @return
     * @author 马莹
     * @since 2018-12-23 09:43:39
     */
    @Override
    public List<ExamRoomModel> findTeacher(String examId, String teacherName) {
        return examRoomDao.findTeacher(examId, teacherName);
    }

    /**
     * 根据考试id 更新开始时间和理论交卷时间
     *
     * @param examId    考试id
     * @param startTime 考试时间
     * @param endTime   理论交卷时间
     * @author 马莹
     * @since 2018-12-24 20:36:36
     */
    @Override
    public boolean updateExamRoomInfomation(String examId, Date startTime, Date endTime) {
        return examRoomDao.updateExamRoomInfomation(examId, startTime, endTime);
    }

    /**
     * 根据考试id筛选考场使用情况
     *
     * @param examId 考试id
     * @return List<ExamRoomModel>
     * @author 马莹
     * @since 2018-12-26 15:18:37
     */
    @Override
    public List<ExamRoomModel> selectExamRoomIng(String examId) {
        return examRoomDao.selectExamRoomIng(examId);
    }

    @Override
    public ExamRoomModel queryExamRootTime(String examRoomId) {
        return examRoomDao.queryExamRootTime(examRoomId);
    }

    /**
     * 根据考试id查询考场
     *
     * @param examId
     * @return
     * @author 于云秀
     * @since 2019年1月5日
     */
    @Override
    public List<ExamRoomModel> selectExamRoomList(String examId, String operator) {
        return examRoomDao.selectExamRoomList(examId, operator);
    }

    /**
     * 根据考试id查询考场和考试信息
     *
     * @param examIdList 考试id集合
     * @return 考试和考场信息集合
     * @author 马莹
     * @since 2019-1-7 09:43:31
     */
    @Override
    public List<ExamExamRoomListModel> selectExamAndExamRoomInfomation(List<String> examIdList) {
        return examRoomDao.selectExamAndExamRoomInfomation(examIdList);
    }


//    public  boolean sendMail(String receive, String subject, String msg  )
//            throws GeneralSecurityException, IOException {
//        if (StringUtils.isEmpty(receive)) {
//            return false;
//        }
//
//        // 发件人电子邮箱
//        final String from = "itoo@tfjybj.com";
//        // 发件人电子邮箱密码
//        final String pass = "TGB123@tgb";
//
//        // 指定发送邮件的主机为 smtp.qq.com
//        String HOST = "smtp.tfjybj.com"; // 邮件服务器
//
//        // 获取系统属性
//        Properties properties = System.getProperties();
//
//        // 设置邮件服务器
//        properties.setProperty("mail.smtp.HOST", HOST);
//
//        properties.put("mail.smtp.auth", "true");
//        MailSSLSocketFactory sf = new MailSSLSocketFactory();
//        sf.setTrustAllHosts(true);
//        properties.put("mail.smtp.ssl.enable", "true");
//        properties.put("mail.smtp.ssl.socketFactory", sf);
//        // 获取默认session对象
//        Session session = Session.getDefaultInstance(properties, new Authenticator() {
//            public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
//                return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
//            }
//        });
//
//        try {
//            // 创建默认的 MimeMessage 对象
//            MimeMessage message = new MimeMessage(session);
//
//            // Set From: 头部头字段
//            message.setFrom(new InternetAddress(from));
//
//            // Set To: 头部头字段
//            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));
//
//            // Set Subject: 主题文字
//            message.setSubject(subject);
//
//            // 创建消息部分
//            BodyPart messageBodyPart = new MimeBodyPart();
//
//            // 消息
//            messageBodyPart.setText(msg);
//
//            // 创建多重消息
//            Multipart multipart = new MimeMultipart();
//
//            // 设置文本消息部分
//            multipart.addBodyPart(messageBodyPart);
//
//            // 附件部分
//            messageBodyPart = new MimeBodyPart();
//
//            // 将上面创建的对象写入本地
////            OutputStream out = new FileOutputStream("MyEmail.eml");
////            message.writeTo(out);
//            // 设置要发送附件的文件路径
//          DataSource source = new FileDataSource("filename");
//          messageBodyPart.setDataHandler(new DataHandler(source));
//
//           messageBodyPart.setFileName("filename");
//            // 处理附件名称中文（附带文件路径）乱码问题
//            messageBodyPart.setFileName(MimeUtility.encodeText("filename"));
//            multipart.addBodyPart(messageBodyPart);
//            System.out.println(multipart.getCount());
//            // 发送完整消息
//            message.setText("");
//            System.out.println(message.getContentID());
//            // 发送消息
//            Transport.send(message);
//            return true;
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
//

//
//    public static class Main {
//
//        public static void main(String[] args) {
//            ExamRoomEntity examRoomEntity = new ExamRoomEntity();
//            examRoomEntity.setLoginTime(new Date());
//            int num = 500;
//
//
//
//
//            Calendar ca = Calendar.getInstance();
//            ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
//            examRoomEntity.setShouldSubmitTime(ca.getTime());
//            System.out.printf("       " + examRoomEntity.getShouldSubmitTime() + "      ");
//        }
//    }
}
